<template>
  <div class="container">
    <div class="tabs-wrapper">
      <nav class="tabs-nav">
        <button
          v-for="tab in tabs"
          :key="tab"
          @click="changeTab(tab)"
          :class="['tab-btn', { active: activeTab === tab }]"
        >
          {{ tab }}
        </button>
      </nav>

      <div class="content-box">
        <MyKeepAlive :active="activeTab" :max="3">
          <component :is="components" :key="activeTab" />
        </MyKeepAlive>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, shallowRef } from "vue";
import Tab1 from "@/components/Tab/Tab1.vue";
import Tab2 from "@/components/Tab/Tab2.vue";
import Tab3 from "@/components/Tab/Tab3.vue";
import MyKeepAlive from "@/components/MyKeepAlive.vue";

// 定义渲染tab的列表
const tabs = shallowRef(["Tab1", "Tab2", "Tab3"]);

// 创建动态组件映射表
const componentsMap = {
  Tab1,
  Tab2,
  Tab3,
};

// 默认激活tab1
const activeTab = shallowRef("Tab1");

// 切换tab
const changeTab = (tab: string) => {
  activeTab.value = tab;
  console.log("activeTab", activeTab.value);
};
// 计算动态组件的渲染逻辑
const components = computed(() => {
  return componentsMap[activeTab.value as keyof typeof componentsMap];
});
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f0f3ff;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.tabs-wrapper {
  width: 100%;
  max-width: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.tabs-nav {
  display: flex;
  gap: 4px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

.tab-btn {
  flex: 1;
  padding: 12px 20px;
  border: none;
  border-radius: 6px;
  background: transparent;
  cursor: pointer;
  transition: all 0.2s;
}

.tab-btn.active {
  background: #4361ee;
  color: white;
}

.tab-btn:hover:not(.active) {
  background: #e9ecef;
}

.content-box {
  padding: 24px;
  min-height: 300px;
}
</style>
